package com.st.emps.staff.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.json.JSONObject;

import com.st.emps.staff.model.StaffModel;
import com.st.emps.staff.service.StaffService;
import com.st.emps.util.Upload;

/**
 * Servlet implementation class StaffUploadServlet
 */
@WebServlet("/StaffUploadServlet")
public class StaffUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private StaffService service = new StaffService();

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String,Object> map = null;
		
		try {
			map=Upload.upload(request);
		} catch ( FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String code = map.get("code").toString();
		
		StaffModel dbmodel = service.selectModel(new StaffModel(code));
		System.out.println(dbmodel.toString()+"----------");
		Upload.delFile(dbmodel.getImage());
		
		List<String> list = (List<String>) map.get("list");
		String image = list.get(0);
		
		StaffModel model = service.selectModel(new StaffModel(code));
		model.setImage(image);
		service.updateImage(model);
		request.getSession().setAttribute("user", model);
		Map<String,String> res = new HashMap<String, String>();
		res.put("code", "0");
		res.put("data", image);
		response.getWriter().print(new JSONObject(res).toString());
	}

}
